package slave

import (
	"backend/internal/common/errorx"
	"backend/internal/db/model"
	"context"
	"fmt"
	"net/http"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SetSlaveAddressLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSetSlaveAddressLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetSlaveAddressLogic {
	return &SetSlaveAddressLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SetSlaveAddressLogic) SetSlaveAddress(req *types.SlaveAddress) (resp *types.BaseResponse, err error) {
	var registerCount int64
	// 先查询符合条件的记录数量
	err = l.svcCtx.GormDB.Model(&model.Register{}).Where("slave_id = ? AND register_type = ?", req.SlaveId, req.RegisterType).Count(&registerCount).Error
	if err != nil {
		errorStr := fmt.Sprintf("查询从站 %d 的寄存器 %s 记录时出错: %v", req.SlaveId, req.RegisterType, err)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}

	if registerCount == 0 {
		// 记录不存在，创建新记录
		newRegister := model.Register{
			SlaveID:      req.SlaveId,
			RegisterType: req.RegisterType,
			StartAddress: req.StartAddress,
			EndAddress:   req.EndAddress,
		}
		result := l.svcCtx.GormDB.Create(&newRegister)
		if result.Error != nil {
			errorStr := fmt.Sprintf("创建从站 %d 的寄存器 %s 记录失败: %v", req.SlaveId, req.RegisterType, result.Error)
			logx.Errorf(errorStr)
			return nil, errorx.NewDefaultError(errorStr)
		}
	} else {
		// 记录存在，更新记录
		result := l.svcCtx.GormDB.Model(&model.Register{}).Where("slave_id = ? AND register_type = ?", req.SlaveId, req.RegisterType).Updates(map[string]interface{}{
			"start_address": req.StartAddress,
			"end_address":   req.EndAddress,
		})
		if result.Error != nil {
			errorStr := fmt.Sprintf("更新从站 %d 的寄存器 %s 地址失败: %v", req.SlaveId, req.RegisterType, result.Error)
			logx.Errorf(errorStr)
			return nil, errorx.NewDefaultError(errorStr)
		}
	}

	return &types.BaseResponse{
		Status: http.StatusOK,
		Msg:    "操作从站寄存器地址成功",
		Data:   true,
	}, nil
}
